<template>
  <div class="selector" v-focus>
    <SelectorInput
        :value="itemValue"
        placeholder="hah"
        @searchOptions="searchOptions"
        @setItemValue="setItemValue"
    ></SelectorInput>
    <SelectorMenu
        :data="data"
        @setItemValue="setItemValue"
        :searchValue="searchValue"
    ></SelectorMenu>
  </div>
</template>

<script>
import SelectorInput from "./input";
import SelectorMenu from "./Menu";
import focus from "../../directives/focus";

import {reactive, toRefs} from "vue";

export default {
  name: "KSelector",
  components: {SelectorInput, SelectorMenu},

  props: {
    data: {
      type: Array
    }
  },
  directives: {
    focus
  },

  setup(props, ctx) {
    let state = reactive({
      itemValue: '',
      searchValue: '',
    })

    //itemValue是给最后用户选择的选项留给input的
    //将item.value返回给用户
    const setItemValue = (item) => {
      state.itemValue = item.text
      console.log(7, state)
      ctx.emit('setItemValue', item.value)
    }

    //searchValue是用户搜索之后提供给Menu用来筛选的,不能作为选择的答案
    const searchOptions = (v) => {
      state.searchValue = v
    }

    return {
      ...toRefs(state),
      setItemValue,
      searchOptions
    }
  }
}
</script>

<style scoped>
  .selector {
    position: relative;
    width: 300px;
    margin: auto;
  }
</style>